using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;

namespace MESTest
{
    public class DoubleLineChart : Canvas
    {
        private Polyline line1;
        private Polyline line2;
        private List<double> values1 = new List<double>();
        private List<double> values2 = new List<double>();
        private List<int> yValues = new List<int>();
        //private const int MaxPoints = 600;
        public double XAxisMax { get; set; } = 100; //x轴最大值，默认100
        public int YAxisMaxPoints { get; set; } = 100;//y轴最大值，默认100

        private Canvas backgroundCanvas = new Canvas();

        public DoubleLineChart()
        {
            this.Background = Brushes.Black;
            this.MinWidth = 100;
            this.MinHeight = 100;
            this.SizeChanged += DoubleLineChart_SizeChanged;

            // 添加背景层
            backgroundCanvas.Background = Brushes.Transparent;
            this.Children.Add(backgroundCanvas);

            // 创建第一条线(亮绿色)
            line1 = new Polyline
            {
                Stroke = Brushes.LimeGreen,
                StrokeThickness = 2
            };

            // 创建第二条线(天蓝色)
            line2 = new Polyline
            {
                Stroke = Brushes.DeepSkyBlue,
                StrokeThickness = 2
            };

            this.Children.Add(line1);
            this.Children.Add(line2);
        }

        private void DoubleLineChart_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            UpdateChart();
        }

        public void AddDataPoint(double value1, double value2)
        {
            //var now = DateTime.Now;

            // 添加新数据
            values1.Add(value1);
            values2.Add(value2);
            yValues.Add(yValues.Count > 0 ? yValues.Last() + 1 : 0);
            if (yValues.Count > YAxisMaxPoints)
            {
                yValues.RemoveAt(0);
                values1.RemoveAt(0);
                values2.RemoveAt(0);
            }

            // 移除超过10分钟的数据
            while (yValues.Count > YAxisMaxPoints)
            {
                values1.RemoveAt(0);
                values2.RemoveAt(0);
                yValues.RemoveAt(0);
            }

            UpdateChart();
        }

        private void UpdateChart()
        {
            if (values1.Count == 0) return;

            // 清除旧刻度线
            backgroundCanvas.Children.Clear();

            double width = this.ActualWidth;
            double height = this.ActualHeight;

            // 绘制X轴刻度线(4等分)
            for (int i = 0; i <= 4; i++)
            {
                double x = i * width / 4;
                backgroundCanvas.Children.Add(new Line()
                {
                    X1 = x,
                    X2 = x,
                    Y1 = 0,
                    Y2 = height,
                    Stroke = Brushes.WhiteSmoke,
                    StrokeThickness = 1,
                    //Stretch = Stretch.Fill
                });
            }

            // 绘制Y轴刻度线(10等分)
            for (int i = 0; i <= 10; i++)
            {
                double y = i * height / 10;
                backgroundCanvas.Children.Add(new Line()
                {
                    X1 = 0,
                    X2 = width,
                    Y1 = y,
                    Y2 = y,
                    Stroke = Brushes.WhiteSmoke,
                    StrokeThickness = 1,
                    //Stretch = Stretch.Fill
                });
            }


            // 确保控件有有效尺寸
            if (width <= 0 || height <= 0)
            {
                System.Diagnostics.Debug.WriteLine($"Invalid chart dimensions: width={width}, height={height}");
                return;
            }

            PointCollection points1 = new PointCollection();
            PointCollection points2 = new PointCollection();

            // 调试日志：输出关键计算参数
            //System.Diagnostics.Debug.WriteLine($"UpdateChart - width: {width}, height: {height}, minValue: {minValue}, maxValue: {maxValue}, valueRange: {valueRange}, values1.Count: {values1.Count}");

            if (values1.Count == 0)
            {
                System.Diagnostics.Debug.WriteLine("No data points to draw");
                return;
            }



            for (int i = 0; i < yValues.Count; i++)
            {
                try
                {
                    // 计算y轴范围
                    int minY = 0;
                    int maxY = YAxisMaxPoints;
                    double yRange = maxY - minY;

                    // 计算Y坐标(基于YAxisMaxPoints)
                    double normalizedY = Math.Max(0, Math.Min(1, (double)yValues[i] / YAxisMaxPoints));
                    double y = height * (1 - normalizedY);

                    // 计算X坐标(两个输入值)，确保在0-1范围内
                    //double normalizedX1 = Math.Max(0, Math.Min(1, values1[i] / XAxisMax));
                    //double normalizedX2 = Math.Max(0, Math.Min(1, values2[i] / XAxisMax));

                    double x1 = width * values1[i] / XAxisMax;
                    double x2 = width * values2[i] / XAxisMax;

                    //System.Diagnostics.Debug.WriteLine($"Point {i}: x1={x1}, x2={x2}, y={y} (time={timestamps[i]})");

                    points1.Add(new Point(x1, y));
                    points2.Add(new Point(x2, y));
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"Error calculating point {i}: {ex.Message}");
                }
            }

            line1.Points = points1;
            line2.Points = points2;

            // 强制重绘
            this.InvalidateVisual();
        }

        protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
        {
            base.OnRenderSizeChanged(sizeInfo);
            UpdateChart();
        }
    }
}